package com.heima.article.listener;

import com.heima.common.constants.article.HotArticleConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author XHui
 * @Since 2024/3/12 16:54
 * @Version 1.0
 */
@Slf4j
@Component
public class HotArticleScoreListener {

    @Resource
    private RedisTemplate redisTemplate;


    /**
     * 热门文章行为处理程序
     * 监听该队列，若该队列不存在，自动创建该队列，queuesToDeclare
     * @param behaviorMessage 行为消息
     */
    @RabbitListener(queuesToDeclare =
    @Queue(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE)
    )
    public void articleOperatedHandler(String behaviorMessage){
        // 1.
        log.info("获取到文章实时热度数据(被操作)：消息内容：{} ", behaviorMessage);

        // 2. 将mq中消息内容存入redis中
        try {
            ListOperations listOperations = redisTemplate.opsForList();
            listOperations.rightPush(
                    HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_LIST,
                    behaviorMessage
            );
            log.info("热门文章行为存入Redis中成功：消息内容：{} ", behaviorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("热门文章行为存入Redis中异常：失败原因：{}", e.getMessage());
        }
    }
}
